package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteEditVoteActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteMyGroupsActivity;
import com.linkage.jz.bankruptcy.activity.Vote.ProVoteVoteDetailActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.PublicProLongNoticeDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * @author AFAP
 * Fragment-表决
 */
public class ProVoteZQFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";

    private RecyclerView mRecyclerView;
    private View emptyView;
    private String mProjectId;
    private String mCreditorId;
    private VoteAdapter mAdapter;
    private List<ProVote> mData;
    private int listType = 1;//这个地方可以根据用户角色判断，债权人还是管理人
    private int myStatus = -1;//按钮状态1参会 2退出参会 3参会表决 4表决
    private PublicProLongNoticeDialog noticeDialog;
    private PublicNoticeDialog makesureDialog;
    private String meetingSureStr = "请您仔细查阅公告的表决事项详情，您可在通知的时间内提前确定是否参会，并在表决开始后行使表决权，或于表决开始后直接参会表决。本表决事项适用《最高人民法院关于适用<中华人民共和国企业破产法>若干问题的规定（三）》第十四条，“债权人委员会决定所议事项应获得全体成员过半数通过”";

    private int page = 1;
    private SwipeRefreshLayout swipe;

    public static ProVoteZQFragment newInstance(int page, String infoid, String CreditorId) {
        Bundle args = new Bundle();
        args.putString("infoid", infoid);
        args.putString("creditorId", CreditorId);
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        ProVoteZQFragment tripFragment = new ProVoteZQFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("zhong", "onCreate: ProVoteZQFragment");
        EventBus.getDefault().register(this);
        mProjectId = getArguments().getString("infoid");
        mCreditorId = getArguments().getString("creditorId", "");
        mData = new ArrayList<>();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_VOTE)) {
            onRefresh();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_vote, container, false);
        swipe = view.findViewById(R.id.swipe);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        emptyView = view.findViewById(R.id.empty_text);
        initAdapter(mData);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipe.setColorSchemeColors(0xff25b6ed, 0xff6dbcdb, 0xfff0b650, 0xffff534e, 0xffbed73d, 0xff04bfbf,
                0xffff530d, 0xff61bc46);
        swipe.setOnRefreshListener(this);
        onRefresh();
    }

    private void initAdapter(List<ProVote> data) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new VoteAdapter(getActivity(), listType, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);
        //设置item点击事件
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProVote item = (ProVote) adapter.getItem(position);
                BundleUtils.saveProVote(item);
                Intent intent = new Intent(getActivity(), ProVoteVoteDetailActivity.class);
                startActivity(intent);
            }
        });
        mAdapter.setEnableLoadMore(true);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                Log.i("zhong", "onLoadMoreRequested: ====" + page);
                getList();
            }
        }, mRecyclerView);
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        page = 1;
        getList();
    }

    class VoteAdapter extends BaseQuickAdapter<ProVote, VoteAdapter.VoteZQHolder> {
        Context context;
        int type;
        int mLayoutId;

        public VoteAdapter(Context context, int type, List<ProVote> str) {
            super(R.layout.fragment_pro_detailpro_vote_item, str);
            this.context = context;
            this.type = type;
            this.mLayoutId = R.layout.fragment_pro_detailpro_vote_item;
        }

        @Override
        public void convert(VoteZQHolder viewHolder, ProVote info) {
            viewHolder.stateText.setText(info.STATUS.get(info.getStatus()));
//            STATUS.put(0, "未发出");
//            STATUS.put(1, "未开始");
//            STATUS.put(2, "进行中");
//            STATUS.put(3, "已结束");
//            STATUS.put(4, "已撤销");
//            STATUS.put(5, "已通过");
//            STATUS.put(6, "未通过");
//            STATUS.put(7, "已删除");
            switch (info.getStatus())
            {
                case 1:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_wks));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg));
                    break;
                case 2:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_jxz));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg_jxz));
                    break;
                case 3:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_yjs));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg_yjs));
                    break;
                case 4:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_ycx));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg_ycx));
                    break;
                case 5:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_ytg));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg_ytg));
                    break;
                case 6:
                    viewHolder.stateText.setTextColor(getResources().getColor(R.color.pro_vote_status_wtg));
                    viewHolder.stateText.setBackground(getResources().getDrawable(R.drawable.pro_vote_fragment_vote_status_bg_wtg));
                    break;
                case 7:
                    break;
                default:
                    break;
            }
            viewHolder.typeText.setText(info.TYPES.get(info.getType()));
            viewHolder.titleText.setText(info.getTitle());
            viewHolder.startText.setText(DateFormatUtils.long2Str(info.getStartTime(), true));
            viewHolder.endText.setText(DateFormatUtils.long2Str(info.getEndTime(), true));
            if(info.isCourtHolding()) {
                viewHolder.tv_vote_courtHolding.setVisibility(View.VISIBLE);
                if(info.getCourtHoldingResult() != 0) {
                    viewHolder.tv_vote_courtHoldingResult.setVisibility(View.VISIBLE);
                    switch (info.getCourtHoldingResult()) {
                        case 1:
                            viewHolder.tv_vote_courtHoldingResult.setText("法院裁定认可");
                            break;
                        case 2:
                            viewHolder.tv_vote_courtHoldingResult.setText("法院裁定不认可");
                            break;
                        case 3:
                            viewHolder.tv_vote_courtHoldingResult.setText("法院裁定通过");
                            break;
                    }
                }else {
                    viewHolder.tv_vote_courtHoldingResult.setVisibility(View.GONE);
                }
            }else {
                viewHolder.tv_vote_courtHolding.setVisibility(View.GONE);
                viewHolder.tv_vote_courtHoldingResult.setVisibility(View.GONE);
            }
            if(BankruptcyApp.curProPermission == 0) {
                viewHolder.stateImage.setVisibility(View.VISIBLE);
                viewHolder.stateImage.setImageResource(ProVote.STATUSIMGS.get(info.getStatus()));
                viewHolder.operateBtn.setVisibility(View.GONE);
            }else {
                viewHolder.stateImage.setVisibility(View.GONE);
                viewHolder.operateBtn.setVisibility(View.VISIBLE);
//                ProVote item = (ProVote) adapter.getItem(position);
                final ProVote mInfo = info;
                switch (info.getStatus()) {
                    case 1://未开始
                    case 2://进行中
                        viewHolder.operateBtn.setVisibility(View.VISIBLE);


                        if(info.getQuitMeeting() == 1)
                        {
                            if(info.getDoVote() == 1) {
                                viewHolder.operateBtn.setText("表决");
                            }else {
//                                if()
                                    viewHolder.operateBtn.setVisibility(View.GONE);
                                viewHolder.operateBtn.setText("退出参会");
                            }
                        }else if(info.getJoinMeeting() == 1) {
                            viewHolder.operateBtn.setText("参会");
                        }else if(info.getMeetingVote() == 1) {
                            viewHolder.operateBtn.setText("参会表决");
                        }else if(info.getDoVote() == 1) {
                            viewHolder.operateBtn.setText("表决");
                        }else{
                            viewHolder.operateBtn.setVisibility(View.GONE);
                        }

                        break;
                    default:
                        viewHolder.operateBtn.setVisibility(View.GONE);
                        break;
                }
                viewHolder.operateBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BundleUtils.saveProVote(mInfo);
                        clickOperateBtn(info);
                    }
                });
            }

        }

        private void clickOperateBtn(ProVote proVote) {
            if(proVote.getQuitMeeting() == 1)
            {
                if(proVote.getDoVote() == 1) {
//                    viewHolder.operateBtn.setText("表决");
                    myStatus = 4;
                }else {
//                    viewHolder.operateBtn.setText("退出参会");
                    myStatus = 2;
                }
            }else if(proVote.getJoinMeeting() == 1) {
//                viewHolder.operateBtn.setText("参会");
                myStatus = 1;
            }else if(proVote.getMeetingVote() == 1) {
                myStatus = 3;
//                viewHolder.operateBtn.setText("参会表决");
            }else if(proVote.getDoVote() == 1) {
//                viewHolder.operateBtn.setText("表决");
                myStatus = 4;
            }


            if(myStatus == 1) {//参会
                if(noticeDialog == null || !noticeDialog.isShowing()) {
                    noticeDialog = new PublicProLongNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                case R.id.ll_close:
                                case R.id.ll_close_lx:
                                case R.id.btn_chancel_notice_lx:
                                    noticeDialog.dismiss();
                                    break;
                                case R.id.btn_save_notice_lx:
                                    noticeDialog.dismiss();
                                    meeting(proVote, 0);
                                    break;
                            }
                        }
                    }, 1, "表决注意事项", meetingSureStr, "我已阅读并充分理解前述信息", "不同意", "同意");
                    noticeDialog.show();
                }
            }else if(myStatus == 2){//退出参会
                if(makesureDialog == null || !makesureDialog.isShowing()) {
                    makesureDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                case R.id.ll_close:
                                    makesureDialog.dismiss();
                                    break;
                                case R.id.btn_chancel_notice:
                                    makesureDialog.dismiss();
                                    break;
                                case R.id.btn_save_notice:
                                    makesureDialog.dismiss();
                                    exitMeeting(proVote);
                                    break;
                            }
                        }
                    }, 1, "提示", "是否确认退出参会？", "取消", "确定");
                    makesureDialog.show();
                }
            }else if(myStatus == 3) {//参会表决
                if(noticeDialog == null || !noticeDialog.isShowing()) {
                    noticeDialog = new PublicProLongNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                case R.id.ll_close:
                                case R.id.ll_close_lx:
                                case R.id.btn_chancel_notice_lx:
                                    noticeDialog.dismiss();
                                    break;
                                case R.id.btn_save_notice_lx:
                                    noticeDialog.dismiss();
                                    meeting(proVote, 1);
                                    break;
                            }
                        }
                    }, 1, "表决注意事项", getResources().getString(R.string.meeting_vote_notice_dialog_txt), "我已阅读并充分理解前述信息", "不同意", "同意");
                    noticeDialog.show();
                }
            }else if(myStatus == 4) {//表决
                if(noticeDialog == null || !noticeDialog.isShowing()) {
                    noticeDialog = new PublicProLongNoticeDialog(getActivity(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            switch (v.getId()) {
                                case R.id.ll_close:
                                case R.id.ll_close_lx:
                                case R.id.btn_chancel_notice_lx:
                                    noticeDialog.dismiss();
                                    break;
                                case R.id.btn_save_notice_lx:
                                    noticeDialog.dismiss();
                                    vote(proVote);
                                    break;
                            }
                        }
                    }, 1, "表决注意事项", getResources().getString(R.string.meeting_vote_notice_dialog_txt), "我已阅读并充分理解前述信息", "不同意", "同意");
                    noticeDialog.show();
                }
            }
        }

        class VoteZQHolder extends BaseViewHolder {

            TextView stateText;
            TextView titleText;
            TextView typeText;
            TextView startText;
            TextView endText;
            TextView tv_vote_courtHolding;
            TextView tv_vote_courtHoldingResult;
            ImageView stateImage;
            Button operateBtn;

            public VoteZQHolder(View view) {
                super(view);
                stateText = view.findViewById(R.id.vote_state);
                titleText = view.findViewById(R.id.tv_vote_name);
                typeText = view.findViewById(R.id.tv_vote_type);
                startText = view.findViewById(R.id.tv_vote_time_start);
                endText = view.findViewById(R.id.tv_vote_time_end);
                tv_vote_courtHolding = view.findViewById(R.id.tv_vote_courtHolding);
                tv_vote_courtHoldingResult = view.findViewById(R.id.tv_vote_courtHoldingResult);
                stateImage = view.findViewById(R.id.iv_voteimg);
                operateBtn = view.findViewById(R.id.btn_operate);
            }
        }
    }

    public void getList() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
//        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null ||"".equalsIgnoreCase(userToken)) {
//            emptyView.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//            return;
//        }

        Network.getAPIService()
            .getVoteList_Creditor(userToken, mProjectId, page, 10)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseSubscriber<JsonObject>() {
                @Override
                public void onNext(JsonObject json) {
                    int code = json.get("code").getAsInt();
                    if (code != 0) {
//                        super.onNext(json);
                        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null ||"".equalsIgnoreCase(userToken)) {
                            emptyView.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                            return;
                        }
                        return;
                    }
                    JsonArray arr = json.getAsJsonObject("data").getAsJsonArray("list");
                    int total = json.getAsJsonObject("data").get("totalCount").getAsInt();
                    List<ProVote> list = ProVote.parse(arr);
                    if (page == 1)
                        mData.clear();
                    page++;
                    mData.addAll(list);
                    if (mData.size() > 0) {
                        //更新UI
                        emptyView.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        //更新UI
                        emptyView.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                    }
                    if (mData.size() < total) {
                        mAdapter.loadMoreComplete();
                    } else {
                        mAdapter.loadMoreEnd();
                    }
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onCompleted() {
                    swipe.setRefreshing(false);
                    mAdapter.setEnableLoadMore(true);
                }

                @Override
                public void onError(Throwable e) {
                    mAdapter.loadMoreFail();
                }
            });
    }

    public void meeting(ProVote proVote, int type) {//type=0参会 1参会后跳转至表决页
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
            .getVoteMeeting_Creditor(userToken, proVote.getId())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseSubscriber<JsonObject>() {
                @Override
                public void onNext(JsonObject json) {
                    super.onNext(json);
                    int code = json.get("code").getAsInt();
                    if (code != 0) {
                        return;
                    }
                    if(type == 1) {
                        vote(proVote);
                    }else {
                        onRefresh();
                    }
                }

                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                }
            });
    }

    public void exitMeeting(ProVote proVote) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network.getAPIService()
            .getVoteExitMeeting_Creditor(userToken, proVote.getId())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseSubscriber<JsonObject>() {
                @Override
                public void onNext(JsonObject json) {
                    super.onNext(json);
                    int code = json.get("code").getAsInt();
                    if (code != 0) {
                        return;
                    }
                    onRefresh();
                }

                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                }
            });
    }

    public void vote(ProVote proVote) {
        if(proVote.isGrouped()) {
            Intent intent = new Intent(getActivity(), ProVoteMyGroupsActivity.class);
            intent.putExtra("voteId", proVote.getId());
            intent.putExtra("creditorId", mCreditorId);
            startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
        }else {
            Intent intent = new Intent(getActivity(), ProVoteEditVoteActivity.class);
            intent.putExtra("vote", false);
            intent.putExtra("voteId", proVote.getId());
            startActivityForResult(intent, ProVoteEditVoteActivity.REQUEST_CODE_VOTE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ProVoteEditVoteActivity.REQUEST_CODE_VOTE && resultCode == RESULT_OK) {
            onRefresh();
        }
    }
}
